
if(!isFunction(onPlayerProcessTick)) eval("function onPlayerProcessTick(){}");
if(!isFunction(Armor, onMount     )) eval("function Armor::onMount     (){}");

package RedBase_HeightControl {
	function Armor::onMount(%data, %player, %obj, %slot) {
		parent::onMount(%data, %player, %obj, %slot);
		RedHeightControl_Update(%obj);
	}
	
	// MoveHandler.dll required - no workaround yet
	function onPlayerProcessTick(%player, %move) {
		parent::onPlayerProcessTick(%player, %move);
		%trig = getWord(%move, 6);
		%jump = (%trig & 8) != 0;
		%crouch = (%trig & 16) != 0;
		
		if(%crouch != %player.RedHeightControl_Crouching) {
			%vehicle = %player.getControlObject();
			if(%vehicle != %player && isObject(%vehicle)) {
				%vclass = %vehicle.getClassName();
				if(%vclass $= "WheeledVehicle" || %vclass $= "FlyingVehicle") {
					%vdata = %vehicle.getDatablock();
					if(%vclass $= "WheeledVehicle" && isFunction(WheeledVehicleData, onTrigger))
						WheeledVehicleData::onTrigger(%vdata, %vehicle, 3, %crouch);
					if(%vclass $= "FlyingVehicle"  && isFunction(FlyingVehicleData , onTrigger))
						FlyingVehicleData ::onTrigger(%vdata, %vehicle, 3, %crouch);
					if(isFunction(%vdata, onTrigger))
						%vdata.onTrigger(%vehicle, %trig, %val);
				}
			}
		}
		
		%player.RedHeightControl_Jumping = %jump;
		%player.RedHeightControl_Crouching = %crouch;
	}
};
activatePackage(RedBase_HeightControl);

function RedHeightControl_Update(%vehicle) {
	if(!isObject(%vehicle)) return;
	cancel(%vehicle.RedHeightControl_Schedule);
	
	%driver = %vehicle.getMountNodeObject(0);
	if(!isObject(%driver)) return;
	
	%data = %vehicle.getDatablock();
	if(!%data.heliUpForce && !%data.heliDownForce) return;
	
	%move =
		%driver.RedHeightControl_Jumping   * %data.heliUpForce -
		%driver.RedHeightControl_Crouching * %data.heliDownForce;
	if(%move != 0) {
		%move = %move / %data.mass * (33/1000);
		%vel = VectorScale(%vehicle.getUpVector(), %move);
		%vehicle.setVelocity(vectorAdd(%vehicle.getVelocity(), %vel));
	}
	
	%vehicle.RedHeightControl_Schedule = schedule(33, 0, RedHeightControl_Update, %vehicle);
}
